import { mapMutations, mapActions, mapState } from "vuex";
import { typeClassName } from "@/pages/config/classNameMap";
import _ from "lodash";
import dayjs from "dayjs";
export default {
  data() {
    return {
      vms: {}, //页面组件vue实例
      //模型
      models: {
        //模型
        qualityItem: {
          ...typeClassName["qualityItem"],
        },
        workUnit: {
          ...typeClassName["workUnit"],
        },
      },
      parentId: "",
      dataSet: {
        //数据集
        rightTableData: [],
        rightTableSelection: [],
        rightTableAllSelection: [],
        leftCurrentIndex: null,
        leftTableData: [],
        leftTableCurrent: null,
        leftTableSelection: [],
        formData: {},
        leftFormData: {},
      },
      onlyRead: false,
      leftFilter: {
       
      },
      rightFilter: {
        
      },
    };
  },
  provide() {
    return {
      anc: this,
    };
  },
  computed: {
    detailAttrs() {
      return {
        ...this.attrs,
        columns: this.attrs.columns.map((item) => {
          item.config["disabled"] = this.onlyRead;
          return item;
        }),
      };
    },
    attrs() {
      return {
        labelWidth: 100,
        labelPosition: "right",
        cols: 3,
        columns: [
          {
            key: "sf_name",
            title: "计划名称",
            minWidth: 200,
            align: "center",
            show: true,
            config: { type: "text" },
          },
          {
            key: "sf_maintainCycle",
            title: "维护周期",
            minWidth: 100,
            align: "center",
            show: true,
            config: {
              type: "select",

              options: [
                { value: "day", label: "日" },
                { value: "week", label: "周" },
                { value: "month", label: "月" },
                { value: "year", label: "年" },
              ],
              event: (row) => {
                this.changeMaintainCycle(row);
              },
            },
          },
          {
            key: "sf_planMaintainDate",
            title: "计划维护时间",
            minWidth: 100,
            align: "center",
            show: true,
            config: {
              type: "text",

              options: this.planMaintainDateOptions,
            },
          },
          {
            key: "if_cycleLength",
            title: "周期时长",
            minWidth: 100,
            align: "center",
            show: true,
            config: {
              type: "text",
            },
          },
          {
            key: "tf_enableTime",
            title: "启用时间",
            minWidth: 100,
            align: "center",
            show: true,
            config: {
              type: "datetime",
            },
          },

          {
            key: "sf_enableStatus",
            title: "是否启用",
            minWidth: 100,
            align: "center",
            show: true,
            config: {
              type: "select",
              options: [
                { value: "是", label: "是" },
                { value: "否", label: "否" },
              ],
            },
          },
        ],
        rules: {
          sf_name: [
            { required: true, message: "请输入计划名称", trigger: "blur" },
          ],
          planBeginDate: [
            { required: true, message: "请输入计划时间", trigger: "change" },
          ],
        },
      };
    },
  },
  created() {
    Object.keys(this.models).map((k) => {
      this.models[k].clz = this.$modelObject.create(this.models[k].modelType);
      this.models[k].clzs = this.$modelObject.create(
        this.models[k].modelType + "Collection"
      );
    });
  },
  mounted() {
    this.$nextTick(() => {
      if (process.env.NODE_ENV === "development") {
        console.log(this);
      }
    });
  },
  methods: {
    /**
     * 逻辑操作：
     * 1. 获取左侧表格数据
     * 2. 点击左侧表格数据，右侧出现表格，并且勾选相关联的数据 leftTableClick
     * **/
    leftLoadPage(
      pageNavigation,
      filter,
      hierValueCondition = "",
      orderBy = "",
      hiddenHierData,
      like = false
    ) {
      let newFilter = {
        ...filter,
        className: this.models.workUnit.className,
        type: this.models.workUnit.type,
        ...this.leftFilter,
      };
      this._$queryByPage(
        this.models["workUnit"].clzs,
        pageNavigation,
        newFilter,
        hierValueCondition,
        orderBy,
        hiddenHierData
      ).then((res) => {
        this.models["workUnit"].clzs.records.forEach((item) => {
          if (
            item.values.sf_maintainCycle == "year" &&
            !!item.values.sf_planMaintainDate
          ) {
            item.values.sf_planMaintainDate = JSON.parse(
              item.values.sf_planMaintainDate
            );
          }
        });
        this.dataSet.leftTableData =
          this.models["workUnit"].clzs.valueRecords;
      });
    },
    /**
     *
     * @param {分页信息} pageNavigation
     * @param {筛选信息} filter
     * @param {*} orderBy
     * @returns
     * 获取右侧表格数据
     */
    rightLoadPage(
      pageNavigation,
      filter,
      hierValueCondition = "",
      orderBy = "",
      hiddenHierData,
      like = false
    ) {
      let newFilter = {
        ...filter,
        className: this.models.qualityItem.className,
        type: this.models.qualityItem.type,
        ...this.rightFilter,
      };
      return this._$queryByPage(
        this.models["qualityItem"].clzs,
        pageNavigation,
        newFilter,
        hierValueCondition,
        orderBy,
        hiddenHierData,
        like
      ).then((res) => {
        this.dataSet.rightTableData =
          this.models["qualityItem"].clzs.valueRecords;

        /**
         * 深拷贝右侧原始数据
         * 注：修改源数据并不能更新勾选装填
         * **/

        let tableData = this._clone(this.dataSet.rightTableData);
        // 判断左侧表格当前选中项是否有数据
        if (this.dataSet.leftTableCurrent) {
          // this.dataSet.leftTableCurrent = this.dataSet.leftTableData[this.dataSet.leftCurrentIndex]
          let ids = this.dataSet.leftTableCurrent.hier.content.map(
            (row) => row.link.linkId
          );
          tableData.forEach((item, index) => {
            // 初始化所有选中状态 为false
            item._checked = false;
            if (ids.includes(item.id)) {
              item._checked = true;
            }
          });
          this.dataSet.rightTableData = tableData;
        }
      });
    },

    rightSelect(selection) {
      let leftIds = this.dataSet.leftTableSelection.map(
        (item) => item.link.linkId
      );
      let selIds = selection.map((item) => item.id);
      let delLinkIds = leftIds.filter((id) => !selIds.includes(id));
      let addLinkIds = selIds.filter((id) => !leftIds.includes(id));
      // let parentId = this._$getHierItemField(
      //   this.dataSet.leftTableData[0].hier,
      //   "巡检设备",
      //   "nodeId"
      // );
      // console.log(parentId);
      if (delLinkIds.length > 0) {
        let delIds = this.dataSet.leftTableCurrent.hier.content
          .filter((item) => delLinkIds.includes(item.link.linkId))
          .map((item) => item.id);

        this.$api.HierInstanceDeleteHier(delIds).then((flag) => {
          this.leftUpdateData();
        });
      }
      if (addLinkIds.length > 0) {
        let dataArray = addLinkIds.map((id) => {
          let item = selection.find((item) => item.id == id).values;
          return {
            containerModel: this.models.qualityItem.modelType,
            containerId: this.dataSet.leftTableCurrent.id,
            parentId: this.parentId,
            linkId: id,
            values: {
              linkId: id,
              sf_code: item.sf_code,
              sf_name: item.sf_name,
              if_equ: item.if_equ,
            },
          };
        });
        this.$api.HierInstanceSaveHier(dataArray).then((flag) => {
          this.leftUpdateData();
        });
      }
    },
    /**
     * 左侧更新数据
     * 注:右侧每次选中取消时,要及时更新左侧选中的数据
     */
    leftUpdateData() {
      this.models["workUnit"].clz
        .queryById(this.dataSet.leftTableCurrent.id)
        .then((res) => {
          this.dataSet.leftTableCurrent =
            this.models["workUnit"].clz.valueRecord;
          this.dataSet.leftTableData[this.dataSet.leftCurrentIndex] =
            this.models["workUnit"].clz.valueRecord;
          this.dataSet.leftTableSelection =
            this.dataSet.leftTableCurrent.hier.content.filter(
              (item) => item.parentId == this.parentId
            );
        });
    },

    /**
     *
     * @param {*} item
     * @param {*} index
     */
    leftClick(item, index) {
      // 存储左侧当前点击的数据
      this.dataSet.leftCurrentIndex = index;
      this.dataSet.leftTableCurrent = this.dataSet.leftTableData[index];
      this.dataSet.leftTableSelection = [];
      this.parentId = this._$getHierItemField(
        this.dataSet.leftTableData[index].hier,
        "巡检设备",
        "nodeId"
      );
      this.dataSet.leftTableSelection =
        this.dataSet.leftTableCurrent.hier.content.filter(
          (item) => item.parentId == this.parentId
        );
      // 初始化右侧表格当前勾选数据
      this.dataSet.rightTableSelection = [];

      // 初始化右侧表格所有勾选数据
      this.dataSet.rightTableAllSelection = [];

      // 初始化右侧表格分页获取数据
      this.vms.equipmentTable.pageNavigation.pageNumber = 1;
      this.rightLoadPage(
        this.vms.equipmentTable.pageNavigation,
        {},
        "",
        "",
        false
      );
    },
    /**
     * 新增巡检计划
     */
    leftTableCreate() {
      this.vms.createModal.show = true;
      this.onlyRead = false;
      // 整理数据格式
      this.dataSet.leftFormData = this.$modelObject.getTpl(
        this.models.workUnit.modelType
      );
      this.dataSet.leftFormData.values.sf_enableStatus = "是";
    },
    /**
     * 查看巡检计划
     * @param {*} row 行数据
     * @param {*} index
     */
    leftTableDetail(row, index) {
      this.dataSet.leftFormData = row;
      this.loadLeftForm(row.sf_maintainCycle);
      this.vms.detailModal.show = true;
      this.onlyRead = true;
    },
    /**
     * 编辑巡检计划
     * @param {*} row 行数据
     * @param {*} index 索引
     */
    leftTableEdit(row, index) {
      this.dataSet.leftFormData = row;
      this.loadLeftForm(row.sf_maintainCycle);
      this.vms.editModal.show = true;
      this.onlyRead = false;
    },

    /**
     * 巡检计划删除
     * @param {*} row 行数据
     * @param {*} index 索引
     */
    leftTableDelete(row, index) {
      let _this = this;
      this._$deleteConfirm(() => {
        _this
          ._$deleteByIds(_this.models["workUnit"].clzs, [row.id])
          .then((res) => {
            // _this.models["workUnit"].clzs.records.splice(index, 1);
            // _this.dataSet.leftTableData =
            //   _this.models["workUnit"].clzs.setValueRecords();
            // _this.vms.inspectionTable.pageNavigation.total =
            //   _this.vms.inspectionTable.pageNavigation.total - 1;
            // let tableData = _this._clone(_this.dataSet.rightTableData);
            // tableData.forEach((item) => {
            //   item._checked = false;
            // });
            // _this.dataSet.rightTableData = tableData;
            this.leftLoadPage(
              _this.vms.inspectionTable.pageNavigation,
              {},
              "",
              "",
              false
            );
          });
      });
    },
    /**
     * 巡检计划多选删除
     * @param {*} row 行数据
     */
    leftTableDeleteMultiple(row) {
      let _this = this;
      this._$deleteConfirm(() => {
        let ids = row.map((items) => String(items.id));
        _this
          ._$deleteByIds({
            ids: ids,
          })
          .then((res) => {
            _this.leftLoadPage(
              _this.vms.inspectionTable.pageNavigation,
              {},
              "",
              "",
              false
            );
          });
      });
    },
    change(type, item) {
      this.changeMaintainCycle(item);
    },

    // 创建巡检项提交
    createModalOk() {
      this.vms.createView.validate((valid) => {
        if (valid) {
          this._merge(this.dataSet.leftFormData, {
            className: this.models.workUnit.className,
            type: this.models.workUnit.type,
            name: dayjs().valueOf(),
          });
          this.models.workUnit.clz
            .add(this.dataSet.leftFormData)
            .then((flag) => {
              if (flag) {
                this.vms.createView.loading = false;
                this.vms.createModal.show = false;
                this.leftLoadPage(
                  this.vms.inspectionTable.pageNavigation,
                  {},
                  "",
                  "",
                  false
                );
              }
            });
        } else {
          this._$requireInfo();
        }
      });
    },
    /**
     * 编辑巡检计划提交
     */
    editModalOk() {
      this.vms.editView.validate((valid) => {
        if (valid) {
          this.models.workUnit.clz.setRecord(
            this.dataSet.leftFormData
          );
          this.models.workUnit.clz.updateById().then((flag) => {
            if (flag) {
              this.vms.editView.loading = false;
              this.vms.editModal.show = false;
              this.leftLoadPage(
                this.vms.inspectionTable.pageNavigation,
                {},
                "",
                "",
                false
              );
            } else {
              this.vms.editView.loading = false;
            }
          });
        } else {
          this._$requireInfo();
        }
      });
    },
  },
};
